#!/usr/bin/python

# temporary script, must be migrate to ruby/rails

# Add to nagios :
# define command{
#        command_name    insert-to-database
#        command_line   /usr/local/nagios/libexec/eventhandlers/insert-to-database.py $HOSTNAME$ "$SERVICEDESC$" $SERVICESTATEID$ $LASTSERVICECHECK$ $SERVICESTATETYPE$ "$SERVICEOUTPUT$" "$SERVICEPERFDATA$"
# }
#
#$HOSTNAME$ $SERVICEDESC$ $SERVICESTATEID$ $LASTSERVICECHECK$
#$SERVICESTATETYPE$ $SERVICEOUTPUT$ $SERVICEPERFDATA$

import sys
import MySQLdb
import time
import logging
import logging.handlers
import datetime

LOG_FILENAME='/var/log/nagios3/import-to-db-'+str(datetime.date.today())+'.log'
logging.basicConfig(filename=LOG_FILENAME,level=logging.INFO,)

in_hostname=sys.argv[1]
in_service=sys.argv[2]
in_state=int(sys.argv[3])
in_lastcheck=int(sys.argv[4])
in_statetype=sys.argv[5] #"HARD" or "SOFT"
in_output=sys.argv[6]
in_perfdata=sys.argv[7]

STATE_OK=0

logging.info('['+str(time.strftime("%Y-%m-%d %H:%M:%S"))+']'+str(in_hostname)+';'+str(in_service)+';'+str(in_state)+';'+str(in_lastcheck)+';'+str(in_statetype)+';'+str(in_output)+';'+str(in_perfdata))

db = MySQLdb.connect(host="", user="", passwd="",db="")
current_alerts = db.cursor()

#def nomDeLaFonction(x, y):
#FUNCTIONS OK
def change_state_nok_to_ok():
  service_cursor=db.cursor()
  #get service ID
  service_cursor.execute("select id from services where hostname='%s' and description='%s'" % (in_hostname,in_service))
  #no id, create it
  if service_cursor.rowcount == 0:
    service_cursor.execute("insert into services (hostname,description) values ('%s','%s')" % (in_hostname,in_service))
    service_cursor.execute("select id from services where hostname='%s' and description='%s'" % (in_hostname,in_service))

  service_row=service_cursor.fetchone()
  serviceID=service_row[0]

  #insert into done
  alerts = db.cursor()
  date_start=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(float(current_alerts_row[3]))) #mysql
  date_end=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(float(in_lastcheck))) #secondes
  duration=in_lastcheck-current_alerts_row[3]
  alerts.execute("insert into alerts (service_id,date_start,date_end,duration,check_status,service_output,service_perfdata) values (%d,'%s','%s',%d,%d,'%s','%s')" % (serviceID,date_start,date_end,duration,current_alerts_row[2],current_alerts_row[4],current_alerts_row[5]))

  #delete from current
  current_alerts.execute("delete from current_alerts where id=%d" % current_alerts_id )
  return

def change_state_ok_to_nok():
  current_alerts.execute("insert into current_alerts (hostname,description,check_status,check_date,service_output,service_perfdata) values('%s','%s',%d,'%d','%s','%s')" % (in_hostname,in_service,in_state,in_lastcheck,in_output,in_perfdata))
  
  return
 
def change_state_nok_to_nok():
  service_cursor=db.cursor()
  #get service ID
  service_cursor.execute("select id from services where hostname='%s' and description='%s'" % (in_hostname,in_service))
  #no id, create it
  if service_cursor.rowcount == 0:
    service_cursor.execute("insert into services (hostname,description) values ('%s','%s')" % (in_hostname,in_service))
    service_cursor.execute("select id from services where hostname='%s' and description='%s'" % (in_hostname,in_service))

  service_row=service_cursor.fetchone()
  serviceID=service_row[0]
 
  #insert into done table
  alerts = db.cursor()
  date_start=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(float(current_alerts_row[3]))) #mysql
  date_end=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(float(in_lastcheck))) #secondes
  duration=in_lastcheck-current_alerts_row[3]
  alerts.execute("insert into alerts (service_id,date_start,date_end,duration,check_status,service_output,service_perfdata) values (%d,'%s','%s',%d,%d,'%s','%s')" % (serviceID,date_start,date_end,duration,current_alerts_row[2],current_alerts_row[4],current_alerts_row[5]))

  #delete from current
  current_alerts.execute("delete from current_alerts where id=%d" % current_alerts_id )
 
  #insert into current the new state
  current_alerts.execute("insert into current_alerts (hostname,description,check_status,check_date,service_output,service_perfdata) values('%s','%s',%d,'%d','%s','%s')" % (in_hostname,in_service,in_state,in_lastcheck,in_output,in_perfdata))
  return

#MAIN, THINGS START HERE

#don't want soft alert
if in_statetype == "SOFT":
  sys.exit()
 
#check for current alert
current_alerts.execute("select hostname,description,check_status,check_date,service_output,service_perfdata,id from current_alerts where hostname='%s' and description='%s'" %(in_hostname,in_service))
current_alerts_row=current_alerts.fetchone()
if current_alerts.rowcount == 1:
  current_alerts_id=current_alerts_row[6] #id
  current_alerts_state=current_alerts_row[2] #check_status

if (in_state == STATE_OK) & (current_alerts.rowcount == 0):
  print "[OK] current is empty, nothing to do"
  logging.info('['+str(time.strftime("%Y-%m-%d %H:%M:%S"))+']'+str(in_hostname)+';'+str(in_service)+' -> current empty, nothing to do')
elif (in_state != STATE_OK) & (current_alerts.rowcount == 0):
  print "[NOK - %s] create new current entry" % in_state
  change_state_ok_to_nok()
  logging.info('['+str(time.strftime("%Y-%m-%d %H:%M:%S"))+']'+str(in_hostname)+';'+str(in_service)+' -> ok to nok')
elif (in_state != STATE_OK) & (current_alerts.rowcount == 1) &(current_alerts_state == in_state):
  print "[NOK - %s] already fill, nothing to do" % in_state
  logging.info('['+str(time.strftime("%Y-%m-%d %H:%M:%S"))+']'+str(in_hostname)+';'+str(in_service)+' -> already fill, nothing to do')
elif (in_state == STATE_OK) & (current_alerts.rowcount == 1) &(current_alerts_state != STATE_OK):
  print "[OK] mv to done"
  change_state_nok_to_ok()
  logging.info('['+str(time.strftime("%Y-%m-%d %H:%M:%S"))+']'+str(in_hostname)+';'+str(in_service)+' -> nok to ok') 
elif (in_state != STATE_OK) & (current_alerts.rowcount == 1) &(current_alerts_state != in_state):
  print "[NOK - %s] mv to another bad status" % in_state
  change_state_nok_to_nok()
  logging.info('['+str(time.strftime("%Y-%m-%d %H:%M:%S"))+']'+str(in_hostname)+';'+str(in_service)+' -> nok to nok')
else:
  print "[%s] unknow input o_O" % in_state
  logging.info('['+str(time.strftime("%Y-%m-%d %H:%M:%S"))+']'+str(in_hostname)+';'+str(in_service)+' -> unknow input o_O')

db.commit ()
db.close ()
